<?php

/**
 * 银行卡相关操作
 */
class BankcardController extends UController
{
	/**
     * 获取用户银行卡信息
     */
    public function  actionIndex()
    {
        $data = array('success'=>0,'msg'=>'');
        $user = User::model();
        $cardinfo = $user->getBankCard($this->userId);
        if($cardinfo[0]==array())
        {
            $data['success'] = -1;
            $data['msg']     = '请绑定银行卡';
        }
        else
        {
            $data['success']  = 1;
            $data['msg']      = 'ok';
            $data['cardinfo'] = $cardinfo;
        }
        $this->setResult($data);
    }
    /**
     * 绑卡显示页面
     */
    public function actionBoundRender()
    {
        $data = array('success'=>0);
        if(Yii::app()->cache2->get('pay_ll_closed'))
        {
            $data['success'] = -1;//支付通道关闭
            $data['msg']     = '支付通道关闭';
        }
        else
        {
            $user = User::model();
            $info = $user->findById($this->userId);
            if(!$info->resetPayPass)
            {
                $data['success'] = -2;
                $data['msg']     = '请先设置支付密码';
            }
            else
            {
                $data['bindFee'] = Yii::app()->params['bindCardFee'];//绑卡费用
                if(!$info->authenticated)//未实名认证
                    $data['success'] = 1;
                elseif(!$info->realAuthenticated) //未真正实名认证
                {
                    $data['name']     = $info->name;
                    $data['identity'] = $info->identity;
                    $card             = $user->getBankCard($this->userId);
                    $cardinfo         = $card[0];
                    if($cardinfo === array())
                        $data['success']  = 2;
                    elseif($cardinfo['supportLL'])
                    {
                        $data['success']        = 3;
                        $data['bankId']         = $cardinfo['bankId'];
                        $data['fullCardNumber'] = $cardinfo['fullCardNumber'];
                        $data['bankName']       = $cardinfo['bankName'];
                    }
                    else
                    {
                        $data['success']  = 6;
                        $data['msg']      = Yii::app()->params['bankCardNotSupport'];
                    }
                }
                else//已真正实名认证
                {
                    $data['name']         = $info->name;
                    $data['starName']     = $info->starName;
                    $data['identity']     = $info->identity;
                    $data['starIdentity'] = $info->starIdentity;
                    $card                 = $user->getBankCard($this->userId);
                    $cardinfo             = $card[0];
                    if($cardinfo === array())
                        $data['success']  = 4;
                    elseif($cardinfo['supportLL'])
                    {
                        $data['success']        = 5;
                        $data['bankId']         = $cardinfo['bankId'];
                        $data['fullCardNumber'] = $cardinfo['fullCardNumber'];
                    }
                    else
                    {
                        $data['success']  = 7;
                        $data['msg']      = Yii::app()->params['bankCardNotSupport'];
                    }
                }
            }
        }
        $this->setResult($data);
    }
    /**
     * 绑定银行卡接口
     */
    public function actionBound()
    {
        $params = array();
        $params['bank_id']     = $this->_post('bank_id');
        $params['card_number'] = $this->_post('card_number');
        $params['user_id']     = $this->userId;
        $params['token']       = $this->token;
        $params['password']    = $this->_post('password');
        $params['name']        = $this->_post('name');
        $params['identity']    = $this->_post('identity');

        $data = array('success' => 0,'msg' => ' ');
        $user = User::model();
        Yii::trace('绑卡 params are'.json_encode($_POST));
        if(!$user->checkPayPass($this->userId,$params['password']))
        {
            $data['success'] = -1;
            $data['msg']     = '交易密码不正确';
        }
        elseif(!preg_match('/^\d{15,19}$/', $params['card_number']))
        {
            $data['msg'] = '请输入正确的银行卡号';
        }
        else
        {
            $check = $user->checkNameIdentity($this->userId,$params['name'],$params['identity']);
            if(!$check['success'])
                $data['msg'] = $check['msg'];
            else
                $data  = $this->boundLL($params);//绑定连连
        }
        $this->setResult($data);
    }
    /**
     * 绑定连连银行卡
     */
    private function boundLL($params)
    {
        $data    = array('success' => 0,'msg' => ' ');
        $gateWay = "ll";
        $bank_code = Helper::getBankCode($params['bank_id']);
        $result  = $this->beforeBind($gateWay,$params['card_number'],$bank_code);
        if($result->success)
        {
            $params['money_order'] = Yii::app()->params['bindCardFee'];
            $params['no_order']    = $result->out_trade_no;
            $params['bind_card']   = 1;
            $sign                  = Helper::llSign($params,1);
            $data['msg']           = $sign['msg'];
            if($sign['success'])
            {
                $data['success']      = 1;
                $data['msg']          = 'ok';
                $data['pay_method']   = 3;
                $data['info']         = array(
                    'out_trade_no' => $result->out_trade_no,
                    'signtime'     => date('YmdHis', time()),
                    'sign'         => $sign['sign'],
                    'notifyUrl'    => $sign['notifyUrl'],
                    'name'         => $sign['name'],
                    'identity'     => $sign['identity'],
                    'no_order'     => $sign['no_order'],
                    'dt_order'     => $sign['dt_order'],
                );
            }
        }
        return $data;
    }

    private function beforeBind($gateWay,$cardNumber,$bank_code)
    {
        $data = array(
            'success'=>false,
            'code'=>10080,
            'msg'=>'系统错误'
        );
        $user         = User::model();
        $out_trade_no = Helper::getTradeUUID($gateWay,$this->userId);
        $amount       = Yii::app()->params['bindCardFee'];
        $result       = $this->noticeRecordBack($amount,$out_trade_no,$bank_code,3,$cardNumber);
        if($result && $result->success)
        {
            $data['success']      = true;
            $data['msg']          = '通知预支付成功';
            $data['out_trade_no'] = $out_trade_no;
        }
        else
            $data['msg'] = $result->errorMessage;
        return (object)$data;
    }
    /**
     * 连连银行卡绑定之后回调接口
     */
    public function actionLlbind()
    {
        $params = array(
            'user_id'  => $this->userId,
            'identity' => $this->_post('identity'),
            'name'     => $this->_post('name'),
            'trade_no' => $this->_post('trade_no'),
        );
        $remote = HttpLib::post($this->javaApi['callback_lianlian'],$params);
        $data = array(
            'success' => 0,
            'msg'     => $remote->errorMsg,
        );
        if($remote->success)
        {
            $data['success'] = 1;
            $data['msg']     = '绑定银行卡成功';
        }
        $this->setResult($data);
    }
    /**
     * 通知后端充值接口
     */
    private function noticeRecordBack($amount,$out_trade_no,$bank_code=null,$paymethod=3,$cardNumber)
    {
        $params =array(
            'user_id'    => $this->userId,
            'token'      => $this->token,
            'amount'     => $amount,
            'method'     => 0,//0线上,1线下
            'pay_method' => $paymethod,//0网银,1易生,2sfpay
            'notice'     => '',
            'trade_no'   => $out_trade_no,
            'bank_code'  => $bank_code,
            'card_no'    => $cardNumber
        );
        $result = HttpLib::post($this->javaApi['account_recharge'], $params);
        return $result;
    }
    /**
     * 解绑银行卡
     */
    public function actionUnbind()
    {
        $data = array('success'=>0,'msg'=>'');
        $card_id = $this->_post('card_id');
        if(!$card_id)
        {
            $data['msg'] = 'card_id参数不能为空';
        }
        else
        {
            $remote = HttpLib::get($this->javaApi['bankcard_unbind'],array('user_id'=>$this->userId,'card_id'=>$card_id));
            $data['msg'] = $remote->errorMsg;
            if($remote!==null && $remote->success)
            {
               $data['success'] = 1 ;
               $data['msg']     = '银行卡注销成功';
            }
            elseif(!$remote->success && $remote->code==20840)
            {
                $data['success'] = -1;
                $data['msg']     = 'ok';
                $data['tips']    = '该卡充值的资金尚未完全提现，为保障您的资金安全，实行资金同卡进同卡出。请将本卡充值的资金全部提现后再进行注销。';
           }
        }
        $this->setResult($data);
    }
    /**
     * 更新银行卡信息(添加省市开户行信息)
     */
    public function actionUpdate()
    {
        $params = array(
            'id'         => $this->_post('id'),
            'province'   => $this->_post('province'),
            'city'       => $this->_post('city'),
            'sub_branch' => $this->_post('branch'),
            'user_id'    => $this->userId,
            'token'      => $this->token,
        );
        $remote = HttpLib::post($this->javaApi['user_bankcard_update'],$params);
        $data = array(
            'msg'     => $remote->errorMsg,
            'success' => 0,
        );
        if($remote->success)
        {
            Yii::app()->cache2->hdel($this->userId.'.Capital','bankCard');
            $data['success'] = 1;
            $data['msg']     = '已完善银行卡信息，可正常提现';
        }
        $this->setResult($data);
    }
}